# decorators.py
from functools import wraps
from django.http import JsonResponse
from .checkToken import validate_custom_token
from utils.crypto import DECRYPT

def token_required(view_func):
    @wraps(view_func)
    def wrapped_view(request, *args, **kwargs):
        auth_header = request.headers.get('Authorization')
        if not auth_header:
            secret = DECRYPT.encrypt({'status': 'Authorization header missing or invalid', 'code': 401,'message':"系统异常"})
            return JsonResponse({'secret': secret}, status=401)
        token_key = auth_header  # 去掉"Token "前缀
        user, error = validate_custom_token(token_key)
        if error:
            secret = DECRYPT.encrypt({'status': 'error', 'code': 401,'message':"token失效"})
            return JsonResponse({'secret': secret}, status=401)
        request.user = user
        return view_func(request, *args, **kwargs)
    return wrapped_view